package com.zipking.cloud.springbootmybatis.current;

import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TaskScheduler {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition taskAvailable = lock.newCondition();
    private final Queue<Runnable> tasks = new LinkedList<>();

    public void schedule(Runnable task, long delay) {
        lock.lock();
        try {
            tasks.add(() -> {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                task.run();
            });
            taskAvailable.signal(); // 通知调度器有新任务
        } finally {
            lock.unlock();
        }
    }

    public void startScheduling() {
        new Thread(this::runScheduler).start();
    }

    private void runScheduler() {
        lock.lock();
        try {
            while (true) {
                while (tasks.isEmpty()) { // 如果没有任务，等待
                    taskAvailable.await();
                }
                Runnable task = tasks.poll();
                task.run();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TaskScheduler scheduler = new TaskScheduler();
        scheduler.schedule(() -> System.out.println("Task 1 executed at " + new Date()), 2000);
        scheduler.schedule(() -> System.out.println("Task 2 executed at " + new Date()), 4000);
        scheduler.startScheduling();
    }
}

